#!/usr/bin/python
# -*- coding=utf8 -*-
"""
Copyright (C) 2010 by lwp
levin108@gmail.com

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the
Free Software Foundation, Inc.,
51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
"""
import os
import platform
from xml.dom import minidom

def check_system():
	system = platform.system()
	if system == 'Windows':
		print 'Currently not support Windows'
		exit(1)

def get_home_dir():
	try:
		return os.environ['HOME']
	except:
		return None

def get_app_dir():
	home_dir = get_home_dir()
	if home_dir is None:
		return None
	app_dir = home_dir + '/.tweets2pdf'
	if not os.path.exists(app_dir):
		os.mkdir(app_dir)
	return app_dir

def get_icon_dir():
	app_dir = get_app_dir()
	if app_dir is None:
		return None
	icon_dir = app_dir + '/icons'
	if not os.path.exists(icon_dir):
		os.mkdir(icon_dir)
	return icon_dir

def get_app_icon():
	if os.path.exists('tweets2pdf.png'):
		return 'tweets2pdf.png'
	if os.path.exists('/usr/share/pixmaps/tweets2pdf.png'):
		return '/usr/share/pixmaps/tweets2pdf.png'
	if os.path.exists('/usr/local/share/pixmaps/tweets2pdf.png'):
		return '/usr/local/share/pixmaps/tweets2pdf.png'
	return None

class tp_cfg:

	def __init__(self):
		pass

	def load(self):
		app_dir = get_app_dir()
		if app_dir is None:
			return False
		cfg_path = app_dir + '/cfg.xml'
		try:
			doc = minidom.parse(cfg_path)
			root = doc.documentElement
			self.font_path = root.getElementsByTagName('font_path')[0].childNodes[0].data
			self.link_color = root.getElementsByTagName('link_color')[0].childNodes[0].data
			return True
		except:
			return False

	def save(self, font_path = {}, link_color = {}):
		impl = minidom.getDOMImplementation()
		doc = impl.createDocument(None, 'cfg', None)
		root = doc.documentElement
		item = doc.createElement('font_path')
		text = doc.createTextNode(font_path)
		item.appendChild(text)
		root.appendChild(item)
		item = doc.createElement('link_color')
		text = doc.createTextNode(link_color)
		item.appendChild(text)
		root.appendChild(item)
		app_dir = get_app_dir()
		if app_dir is None:
			return False
		self.font_path = font_path
		self.link_color = link_color
		cfg_file = open(app_dir + '/cfg.xml', 'w')
		cfg_file.write(root.toxml())
		cfg_file.close()
		return True
